package com.tnl.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.jfinal.wxaapp.api.WxaTemplate;
import com.mysql.jdbc.StringUtils;
import com.tnl.app.dao.*;
import com.tnl.app.entity.*;
import com.tnl.app.entity.Dictionary;
import com.tnl.app.service.IEmployeeService;
import com.tnl.app.service.IPersonService;
import com.tnl.app.service.IRecommendService;
import com.tnl.app.service.UserService;
import com.tnl.app.service.impl.MailService;
import com.tnl.app.service.impl.SMSService;
import com.tnl.app.vo.JobRequestVo;
import com.tnl.app.vo.PageVo;
import com.tnl.base.Const;
import com.tnl.base.SystemConfig;
import com.tnl.base.web.JsonController;
import com.tnl.utils.*;
import org.apache.commons.io.IOUtils;
import org.apache.poi.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/index")
public class IndexController extends JsonController {
    @Autowired
    private UserService userService;
    @Autowired
    private AdcarouselDAO adcarouselDAO;
    @Autowired
    private AdChannelDAO adChannelDAO;
    @Autowired
    private ArticleDAO articleDAO;
    @Autowired
    private JobDAO jobDAO;
    @Autowired
    private CityDAO cityDAO;
    @Autowired
    private CompanyDAO companyDAO;
    @Autowired
    private RecommendDAO recommendDAO;
    @Autowired
    private RecommendRecordDAO recommendRecordDAO;
    @Autowired
    private InterViewDAO interViewDAO;
    @Autowired
    private InterViewRecordDAO interViewRecordDAO;
    @Autowired
    private JobTitleDAO jobTitleDAO;
    @Autowired
    private WxAppUserDAO wxAppUserDAO;
    @Autowired
    private DomainDAO domainDAO;
    @Autowired
    private HunterDAO hunterDAO;
    @Autowired
    private IPersonService personService;
    @Autowired
    private IRecommendService recommendService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private SMSService smsService;
    @Autowired
    private MailService mailService;

    @Autowired
    SysPictureDao sysPictureDao;

    @Autowired
    DictionaryDAO dictionaryDAO;

    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    /**
     * 微信小程序登陆
     *
     * @param response
     * @param code
     * @throws IOException
     */
    @RequestMapping(value = "wxlogin")
    public void wxLogin(HttpServletResponse response, String code) throws IOException {
        JSONObject jsonObject;
        String appId, appSecret;
        String deString = null;
        appId = SystemConfig.getProperties("appid");
        appSecret = SystemConfig.getProperties("appscret");
        try {
            JSONObject aString = UserManagerUtil.getAccessToken(appId, appSecret, code);
            jsonObject = aString;
            System.out.println("jsonobject=" + jsonObject);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            String a = org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e);
            jsonObject = JSONObject.parseObject("{\"errcode\":\"" + a + "\"}");
            e.printStackTrace();
            deString = "error";
        }
        this.successJson(jsonObject.toString(), "登录", response);
    }

    /**
     * getuserInfo
     *
     * @param response
     * @param code
     * @param iv
     * @param encryptedData
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("/getwxUserInfo")
    public void getwxUserInfo(HttpServletResponse response, String code, String iv, String encryptedData)
            throws ServletException, IOException {
        WxAppUser wxappuser = null;
        JSONObject jsonObject;
        jsonObject = UserManagerUtil.getWxUserInfo(code, iv, encryptedData);
        wxappuser = UserManagerUtil.getSNSUserInfo(jsonObject);
        String openId = wxappuser.getOpenid();
        insertUser(wxappuser, openId);
        this.successJson(jsonObject, "获取登陆用户信息", response);
    }

    /**
     * 医人才微信小程序登陆
     *
     * @param response
     * @param code
     * @throws IOException
     */
    @RequestMapping(value = "wxposilogin")
    public void wxPositionLogin(HttpServletResponse response, String code) throws IOException {
        JSONObject jsonObject;
        String appId, appSecret;
        String deString = null;
        appId = SystemConfig.getProperties("appid_med");
        appSecret = SystemConfig.getProperties("appscret_med");
        try {
            JSONObject aString = UserManagerUtil.getAccessToken(appId, appSecret, code);
            jsonObject = aString;
            System.out.println("jsonobject=" + jsonObject);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            String a = org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e);
            jsonObject = JSONObject.parseObject("{\"errcode\":\"" + a + "\"}");
            e.printStackTrace();
            deString = "error";
        }
        this.successJson(jsonObject.toString(), "登录", response);
    }

    /**
     * 医人才微信小程序登陆
     *
     * @param response
     * @param code
     * @throws IOException
     */
    @RequestMapping(value = "wxmedlogin")
    public void wxMedTalentLogin(HttpServletResponse response, String code) throws IOException {
        JSONObject jsonObject;
        String appId, appSecret;
        String deString = null;
        appId = SystemConfig.getProperties("appid_medtalent");
        appSecret = SystemConfig.getProperties("appscret_medtalent");
        try {
            JSONObject aString = UserManagerUtil.getAccessToken(appId, appSecret, code);
            jsonObject = aString;
            System.out.println("jsonobject=" + jsonObject);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            String a = org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e);
            jsonObject = JSONObject.parseObject("{\"errcode\":\"" + a + "\"}");
            e.printStackTrace();
            deString = "error";
        }
        this.successJson(jsonObject.toString(), "登录", response);
    }

    /**
     * 医人才getuserInfo
     *
     * @param response
     * @param code
     * @param iv
     * @param encryptedData
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("/getUserInfo")
    public void getUserInfo(HttpServletResponse response, String code, String iv, String encryptedData)
            throws ServletException, IOException {
        WxAppUser wxappuser = null;
        JSONObject jsonObject;
        jsonObject = UserManagerUtil.getWxInfo(code, iv, encryptedData);
        wxappuser = UserManagerUtil.getSNSUserInfo(jsonObject);
        String openId = wxappuser.getOpenid();
        insertUser(wxappuser, openId);
        this.successJson(jsonObject, "获取登陆用户信息", response);
    }

    @RequestMapping("/createUserInfo")
    public void createUserInfo(HttpServletResponse response, String openId, String unionid, String nickName, String avatarUrl, String gender, String language, String province, String city, String country) {
        WxAppUser wxappuser = new WxAppUser();
        Long count = wxAppUserDAO.getOpenId(openId);
        if (count < 1) {
            wxappuser.setOpenid(openId);
            wxappuser.setUnionid(unionid);//20180516
            wxappuser.setNickname(nickName.replaceAll("[\ue000-\uefff]", ""));
            wxappuser.setAvatar(avatarUrl);
            wxappuser.setGender(Integer.parseInt(gender));
            wxappuser.setLanguage(language);
            wxappuser.setProvince(province);
            wxappuser.setCity(city);
            wxappuser.setCountry(country);
            int result = wxAppUserDAO.saveUserInfo(wxappuser);
            this.successJson(result, "获取登陆用户信息", response);
        } else {
            wxappuser.setOpenid(openId);
            wxappuser.setUnionid(unionid);//20180516
            wxappuser.setNickname(nickName.replaceAll("[\ue000-\uefff]", ""));
            wxappuser.setAvatar(avatarUrl);
            wxappuser.setGender(Integer.parseInt(gender));
            wxappuser.setLanguage(language);
            wxappuser.setProvince(province);
            wxappuser.setCity(city);
            wxappuser.setCountry(country);
            int result = wxAppUserDAO.update(wxappuser);
            this.successJson(result, "update登陆用户信息sucess", response);
        }
        this.successJson(count, "已存在", response);
    }


    /**
     * 移动轮播图
     *
     * @param response
     * @param type
     */
    @RequestMapping(value = "getAdcarouse")
    public void getAdcarouse(HttpServletResponse response, Integer type) {
        List<Adcarousel> ad = adcarouselDAO.getByType(type);
        this.successJson(ad, "移动首页轮播图", response);
    }

    /**
     * 职业经纪人
     *
     * @param response
     */
    @RequestMapping(value = "getTopHunter")
    public void getHunterList(Integer size, HttpServletResponse response) {
        List<Hunter> list = hunterDAO.getHunterList(0, size);
        for (Hunter hunter : list) {
            hunter.setImageUrl(hunter.getImageUrl() != null ? Const.IMAGE_PATH + hunter.getImageUrl() : Const.IMAGE);
        }
        this.successJson(list, "推荐顾问", response);
    }

    /**
     * channel
     *
     * @param response
     */
    @RequestMapping(value = "getChannel")
    public void getChannel(HttpServletResponse response) {
        List<Channel> list = adChannelDAO.getByContent();
        this.successJson(list, "channel", response);
    }

    /**
     * art
     *
     * @param response
     */
    @RequestMapping(value = "getArticle")
    public void getArticle(HttpServletResponse response, Integer pageSize, Integer page) {
        int totalNum = articleDAO.getTotalNumForArtByHot();
        int pageNum = getPageNum(totalNum, pageSize);
        int offset = (page - 1) * pageSize;
        List<ArticleInfo> job = articleDAO.getByContent(offset, pageSize);
        this.successJson(new PageVo(job, pageNum), "article", response);
    }

    @RequestMapping(value = "getArticleDetail")
    public void getArticleDetail(HttpServletResponse response, Integer id) {
        ArticleInfo art = articleDAO.getById(id);
        this.successJson(art, "article", response);
    }

    /**
     * 职道主页展示3条-精选好文设定type1
     */
    @RequestMapping(value = "getTopArticleByHot")
    public void getTopArticleByHot(HttpServletResponse response, Integer pageSize) {
        List<ArticleInfo> arts = articleDAO.getArticleByHotList(0, pageSize);
        this.successJson(arts, "精选好文主页展示", response);
    }

    /**
     * 医人才主页展示3条-精选好文设定type3
     */
    @RequestMapping(value = "getYrcTopArticleByHot")
    public void getYrcTopArticleByHot(HttpServletResponse response, Integer pageSize) {
        List<ArticleInfo> arts = articleDAO.getYrcArticleByHotList(0, pageSize);
        this.successJson(arts, "精选好文主页展示", response);
    }

    /**
     * art
     *
     * @param response
     */
    @RequestMapping(value = "getYrcArticle")
    public void getYrcArticle(HttpServletResponse response, Integer pageSize, Integer page) {
        int totalNum = articleDAO.getTotalNumForYrcArtByHot();
        int pageNum = getPageNum(totalNum, pageSize);
        int offset = (page - 1) * pageSize;
        List<ArticleInfo> job = articleDAO.getByYrcContent(offset, pageSize);
        this.successJson(new PageVo(job, pageNum), "article", response);
    }

    /**
     * 主页展示5条-最新职位
     */
    @RequestMapping(value = "getTopJobByHot")
    public void getTopJobByHot(JobRequestVo jobRequestVo, HttpServletResponse response, Integer pageSize) {
        List<Integer> companyIds = null;
        if (!StringUtils.isEmptyOrWhitespaceOnly(jobRequestVo.getKeyWord())) {
            List<Company> companyList = companyDAO.searchCompany(0, 100, jobRequestVo.getKeyWord());
            if (companyList != null && companyList.size() > 0) {
                companyIds = companyList.parallelStream().map(Company::getId).collect(Collectors.toList());
                jobRequestVo.setCompanyIds(companyIds);
            }
        }


        List<JobDesc> job = jobDAO.getJobByHotList(jobRequestVo, 0, pageSize);
        for (JobDesc jobDesc : job) {
            // get city
            int cityId = jobDesc.getCityId();
            City city = cityDAO.getById(cityId);
            if (city != null) {
                jobDesc.setCityName(city.getName());
            }
            // get company
            Company company = companyDAO.getById(jobDesc.getCompanyId());
            if (company != null) {
                jobDesc.setCompanyName(company.getName());
                jobDesc.setEnterprise_logo(company.getLogoIcon());
            }

            // get expiredate
            long data = jobDesc.getExpiredDate();
            jobDesc.setExpiredDateStr(DateUtil.getDateStr(data));
            // get domain
            Domain domain = domainDAO.getById(jobDesc.getDomainID());
            if (domain != null) {
                jobDesc.setDomainName(domain.getName());
            }
            jobDesc.setCreateTime(DateUtil.getDateStr(jobDesc.getCreateDate()));
        }
        job.stream().parallel().filter(s -> !StringUtils.isEmptyOrWhitespaceOnly(s.getKeywords())).peek(s -> {
            setKeyWords(s);
        }).collect(Collectors.toList());
        this.successJson(job, "最新职位主页展示", response);
    }

    private void setKeyWords(JobDesc s) {
        String keywords = s.getKeywords();
        String[] tagList = keywords.split(",");
        List<String> tags = Arrays.asList(tagList);
        List<String> keyList = tags.stream().filter(p->!Objects.equals("0", p)).collect(Collectors.toList());
        if(keyList == null || keyList.size() <= 0){
            return;
        }
        List<Dictionary> dictionary = dictionaryDAO.listByTypeAndValue("position_slogan", keyList);
        List<String> tag = dictionary.stream().map(Dictionary::getLabel).collect(Collectors.toList());
        s.setTagList(tag);
    }

    /**
     * 移动主页内容板块
     *
     * @param response
     * @param type
     */
    @RequestMapping(value = "getAdContent")
    public void getAdContent(HttpServletResponse response, Integer type) {
        List<Adcarousel> ad = adcarouselDAO.getByContent(type);
        this.successJson(ad, "移动主板内容图", response);
    }

    /**
     * 最新职位
     *
     * @param response
     */
    @RequestMapping(value = "getJobByHot")
    public void getJobByHot(JobRequestVo jobRequestVo, Integer page, Integer size, HttpServletResponse response) {
        int totalNum = jobDAO.getTotalNumForJobByHot(jobRequestVo);
        int pageNum = getPageNum(totalNum, size);
        int offset = (page - 1) * size;
        List<Integer> companyIds = null;
        if (!StringUtils.isEmptyOrWhitespaceOnly(jobRequestVo.getKeyWord())) {
            List<Company> companyList = companyDAO.searchCompany(0, 100, jobRequestVo.getKeyWord());
            if (companyList != null && companyList.size() > 0) {
                companyIds = companyList.parallelStream().map(Company::getId).collect(Collectors.toList());
                jobRequestVo.setCompanyIds(companyIds);
            }
        }
        List<JobDesc> job = jobDAO.getJobByHotList(jobRequestVo, offset, size);

        for (JobDesc jobDesc : job) {
            // get city
            int cityId = jobDesc.getCityId();
            City city = cityDAO.getById(cityId);
            if (city != null) {
                jobDesc.setCityName(city.getName());
            }
            // get company
            Company company = companyDAO.getById(jobDesc.getCompanyId());
            if (company != null) {
                jobDesc.setCompanyName(company.getName());
                jobDesc.setEnterprise_logo(company.getLogoIcon());
            }
            // get expiredate
            long data = jobDesc.getExpiredDate();
            jobDesc.setExpiredDateStr(DateUtil.getDateStr(data));
            //get
            // get domain
            Domain domain = domainDAO.getById(jobDesc.getDomainID());
            if (domain != null) {
                jobDesc.setDomainName(domain.getName());
            }

            jobDesc.setCreateTime(DateUtil.getDateStr(jobDesc.getCreateDate()));
        }
        job.stream().parallel().filter(s -> !StringUtils.isEmptyOrWhitespaceOnly(s.getKeywords())).peek(s -> {
            setKeyWords(s);
        }).collect(Collectors.toList());
        this.successJson(new PageVo(job, pageNum), "最新职位", response);
    }

    @RequestMapping(value = "similarPosi")
    public void similarPosi(HttpServletResponse response, String unionid, Integer jobid) {
        List<JobDesc> job = null;
        if (unionid != null) {
            EmployeePerson emp = employeeService.getEmpPersonByUnionid(unionid);
            JobDesc jobdesc = jobDAO.getById(jobid);
            Date todayDate = new Date();
            long today = todayDate.getTime();
            job = jobDAO.similarPosi2(emp.getRoleId(), emp.getExpectJob(), jobdesc.getRoleid(), jobdesc.getExpectJobId(), today, jobid);
            for (JobDesc jobDesc : job) {
                // get city
                int cityId = jobDesc.getCityId();
                City city = cityDAO.getById(cityId);
                jobDesc.setCityName(city.getName());
                // get company
                Company company = companyDAO.getById(jobDesc.getCompanyId());
                jobDesc.setCompanyName(company.getName());
                jobDesc.setEnterprise_logo(company.getLogoIcon());
                Domain domain = domainDAO.getById(jobDesc.getDomainID());
                if (domain != null) {
                    jobDesc.setDomainName(domain.getName());
                }
                // get expiredate
                long data = jobDesc.getExpiredDate();
                jobDesc.setExpiredDateStr(DateUtil.getDateStr(data));
            }
        }
        job.stream().parallel().filter(s -> !StringUtils.isEmptyOrWhitespaceOnly(s.getKeywords())).peek(s -> {
            setKeyWords(s);
        }).collect(Collectors.toList());
        this.successJson(job, "相似职位", response);
    }
/*	@RequestMapping(value = "similarPosi")
	public void similarPosi(Integer page,Integer size,HttpServletResponse response,String name) {
		int totalNum=jobDAO.getTotalNumForsimilarPosi(name);
		int pageNum=getPageNum(totalNum,size);
		int offset=(page-1)*size;
		List<JobDesc> job = jobDAO.similarPosi(offset,size,name);
		for (JobDesc jobDesc : job) {
			// get city
			int cityId = jobDesc.getCityId();
			City city = cityDAO.getById(cityId);
			jobDesc.setCityName(city.getName());
			// get company
			Company company = companyDAO.getById(jobDesc.getCompanyId());
			jobDesc.setCompanyName(company.getName());
			// get expiredate
			long data = jobDesc.getExpiredDate();
			jobDesc.setExpiredDateStr(DateUtil.getDateStr(data));
		}
		this.successJson(new PageVo(job,pageNum), "相似职位", response);
	}*/

    /**
     * 精准匹配
     *
     * @param response
     */
    @RequestMapping(value = "serachJobByCandidate")
    public void serachJobByCandidate(HttpServletResponse response, String unionid, Integer page, Integer size) {
        //unionid="oVCCz1LdYLYknfVIEx6gcg40FGZg";
        //Employee emp = employeeDAO.getByOpenId(openid);
        if (unionid != null) {
            Employee emp = employeeService.getEmpByUnionid(unionid);
            int PAGE_SIZE = 8;
            if (emp != null) {
                Person person = employeeService.getById(emp.getPersonId());
                if (person != null) {
                    Integer expectJob = emp.getExpectJob();
                    long roleId = person.getRoleId();
                    //String companys = emp.getExpectCompanies();
                    int companyId = person.getCompanyId();
                    int majorDomainId1 = emp.getMajorDomainId1();
                    int majorDomainId2 = emp.getMajorDomainId2();
                    int majorDomainId3 = emp.getMajorDomainId3();
                    int expectCompany1 = emp.getExpectCompany1();
                    int expectCompany2 = emp.getExpectCompany2();
                    int expectCompany3 = emp.getExpectCompany3();
                    StringBuilder sbcom = new StringBuilder();
                    if (expectCompany1 > 0) {
                        sbcom.append(expectCompany1);
                    }
                    if (expectCompany2 > 0) {
                        sbcom.append("," + expectCompany2);
                    }
                    if (expectCompany3 > 0) {
                        sbcom.append("," + expectCompany3);
                    }
                    String companys = "" + sbcom;
                    StringBuilder sb = new StringBuilder();
                    if (majorDomainId1 > 0) {
                        sb.append(majorDomainId1);
                    }
                    if (majorDomainId2 > 0) {
                        sb.append("," + majorDomainId2);
                    }
                    if (majorDomainId3 > 0) {
                        sb.append("," + majorDomainId3);
                    }
                    String ids = "" + sb;
                    int cityId = person.getCityId();
                    Date todayDate = new Date();
                    long today = todayDate.getTime();
                    int totalNum = jobDAO.searchJobsByDomainCount(expectJob, roleId,
                            companyId, companys, today, cityId, ids);
                    int pageNum = getPageNum(totalNum, size);
                    int offset = (page - 1) * size;
                    List<JobDesc> jobA = jobDAO.searchJobsByDomain(expectJob, roleId, companyId, companys, ids, today,
                            cityId, offset, PAGE_SIZE);
                    List<JobDesc> jobB = jobDAO.searchJobsByDomainPAGE6(expectJob, roleId, companyId, companys, ids, today,
                            cityId, offset, PAGE_SIZE);
                    //  使用hashmap  进行去重的问题
                    //筛选平台  update 0707
                    HashMap<String, JobDesc> jobMap = new HashMap<String, JobDesc>();
                    for (JobDesc job : jobA) {
                        if (job.getPlatformID() != 2) {
                            jobMap.put(job.getJobCode(), job);
                        }
                    }
                    for (JobDesc job : jobB) {
                        //  如果listB  中的名称不相同的加入到listA 中的 如果有顺序的安排的可以对hashmap  改为LinkedHashMap  这样的插入是有序的加入的
                        if (job.getPlatformID() != 2 && !jobMap.containsKey(job.getJobCode())) {
                            jobMap.put(job.getJobCode(), job);
                        }
                    }

                    // 对这个map进行遍历，补充信息
                    Iterator<Map.Entry<String, JobDesc>> iterator = jobMap.entrySet().iterator();
                    List<JobDesc> jobsmap = new ArrayList<JobDesc>();
                    while (iterator.hasNext()) {
                        Map.Entry<String, JobDesc> next = iterator.next();
                        JobDesc value = next.getValue();
                        jobsmap.add(value);
                    }
                    for (JobDesc jobDesc : jobsmap) {
                        // get city
                        int cityId2 = jobDesc.getCityId();
                        City city = cityDAO.getById(cityId2);
                        if (city != null) {
                            jobDesc.setCityName(city.getName());
                        }
                        // get company
                        Company company = companyDAO.getById(jobDesc.getCompanyId());
                        if (company != null) {
                            jobDesc.setCompanyName(company.getName());
                            jobDesc.setEnterprise_logo(company.getLogoIcon());
                        }
                        // get expiredate
                        long data = jobDesc.getExpiredDate();
                        jobDesc.setExpiredDateStr(DateUtil.getDateStr(data));
                        // get domain
                        Domain domain = domainDAO.getById(jobDesc.getDomainID());
                        if (domain != null) {
                            jobDesc.setDomainName(domain.getName());
                        }
                    }

                    jobsmap.stream().parallel().filter(s -> !StringUtils.isEmptyOrWhitespaceOnly(s.getKeywords())).peek(s -> {
                        setKeyWords(s);
                    }).collect(Collectors.toList());
                    this.successJson(new PageVo(jobsmap, pageNum), "精准匹配", response);
                }
            } else {
                this.errorJson(emp, "未查询到此人请去注册完善个人信息", response);
            }
        } else {
            this.errorJson(unionid, "未查询到此人请去注册完善个人信息", response);
        }

    }


    /**
     * 职位详情
     *
     * @param response
     */
    @RequestMapping(value = "jobdetail")
    public void jobdetail(HttpServletResponse response, Integer jobid) {
        System.out.println("jobdetail function STEP 1");
        JobDesc job = jobDAO.getById(jobid);
        //get company
        Company company = companyDAO.getById(job.getCompanyId());
        job.setCompanyName(company.getName());
        job.setCompanyAddress(company.getAddress());
        job.setEnterprise_logo(company.getLogoIcon());
        job.setUrl(company.getWxurl());
        job.setCompanyPicture(company.getImage());

        long num = jobDAO.getSumByCompanyId(company.getId());
        job.setHotJobNum(num);
        //get city
        int cityId = job.getCityId();
        if (!StringUtils.isEmptyOrWhitespaceOnly(job.getKeywords())) {
            setKeyWords(job);
        }


        if (cityId != 0) {
            City city = cityDAO.getById(cityId);

            job.setCityName(city.getName());
        }


        //get expired date
        long data = job.getExpiredDate();
        job.setExpiredDateStr(DateUtil.getDateStr(data));

        //show hr information
        Employer employer = userService.getEmployerId(job.getCreatedby());
        if (employer != null) {
            System.out.println("employer headurl" + employer.getHeadImgUrl());
            job.setHrHeadImgUrl(employer.getHeadImgUrl());
            job.setEnglishname(employer.getEnglishname());
            job.setRoleName(employer.getRoleName());
        }
        this.successJson(job, "职位详情", response);
    }

    /**
     * 是否已被推荐该职位
     *
     * @param response
     * @param jobid
     */
    @RequestMapping(value = "isExistRecommendself")
    public void isAlreadySelfRecommended(String unionid, HttpServletRequest request, HttpServletResponse response, int jobid) {
        //unionid="oVCCz1AFLP-9mRGqOs8k_0w6V13Y";
        String resStr = "";
        String msg = "";
        if (unionid != null) {
            Employee employee = employeeService.getEmpByUnionid(unionid);
            if (employee == null) {
                resStr = "noPhone";
                msg = "无手机号码";
            } else {
                String phone = employee.getPhone();
                RecommendedPerson bol = recommendDAO.getByJobAndPhone(jobid, phone);
                if (bol != null) {
                    resStr = "hasRec";
                    msg = "已应聘该职位";
                } else {
                    resStr = "notRec";
                    msg = "未应聘该职位";
                }
            }
        }
        successJson(resStr, msg, response);
    }

    /**
     * 我的资料
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "isHaveResume")
    public void isHaveResume(String unionid, HttpServletRequest request, HttpServletResponse response) {
        JSONObject json = new JSONObject();
        String msg = "";
        //unionid="oVCCz1AFLP-9mRGqOs8k_0w6V13Y
        System.out.println("unionid is" + unionid);
        Employee employee = employeeService.getEmpByUnionid(unionid);

        if (employee != null && employee.getState() != null) {
            if (employee.getState().equals("binded")) {
                msg = "已绑定过手机号继续完善简历";
                logger.info("emmployee state=" + employee.getState() + ",msg=" + msg);
                this.successJson(employee.getState(), msg, response);
            } else if (employee.getState().equals("generated")) {
                msg = "生成过验证码未绑定进一步手机验证";
                logger.info("emmployee state=" + employee.getState() + ",msg=" + msg);
                this.successJson(employee.getState(), msg, response);
            } else if (employee.getState().equals("completed")) {
                Person person = employeeService.getById(employee.getPersonId());
                msg = "已有简历";
                json.put("employee", employee);
                json.put("person", person);
                logger.info("emmployee state=" + employee.getState() + ",msg=" + msg);
                this.successJson(json, msg, response);
            }
        } else {
            msg = "去完善个人资料";
            System.out.println("currt employee is null or state is null");
            this.successJson(null, msg, response);
        }
    }

    /**
     * 我的简历
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "isExitResume")
    public void isExitResume(String unionid, HttpServletRequest request, HttpServletResponse response) {
        String msg = "";
        //unionid="oVCCz1AFLP-9mRGqOs8k_0w6V13Y
        System.out.println("unionid is" + unionid);
        Employee employee = employeeService.getEmpByUnionid(unionid);
        if (employee.getState() != null) {
            if (employee.getState().equals("binded")) {
                msg = "已绑定过手机号继续完善简历";
                this.errorJson(0, msg, response);
            } else if (employee.getState().equals("generated")) {
                msg = "生成过验证码未绑定进一步手机验证";
                this.errorJson(0, msg, response);
            } else if (employee.getState().equals("completed")) {
                long count = personService.getCountDocByPersonId(employee.getPersonId());
                msg = "已有简历";
                this.successJson(count, msg, response);
            }
        } else {
            msg = "去完善个人资料";
            this.errorJson(0, msg, response);
        }
    }

    @RequestMapping(value = "uploadFile")
    public void uploadFile(MultipartFile file, String unionid, HttpServletRequest request, HttpServletResponse response) {
        String path = Const.BASE_PATH;
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        FileOutputStream fos;
        Employee employee = employeeService.getEmpByUnionid(unionid);
        Integer personid = employee.getPersonId();
        String documentId = "doc-" + DateUtil.currentTimeStr() + personid;
        String newFileName = documentId + "." + suffix;// 避免冲突
        String filePath = path + newFileName;
        logger.info(filePath);
        // 重命名
        //documentId=FileUtils.createDocument(FileUtils.createClient(), toFile, fileName, suffix, Global.SUCCESS, Global.PUBLIC, Global.H5);//外部
        //System.out.println(fileName+",documentId=");
        try {
            fos = FileUtils.openOutputStream(new File(filePath));
            IOUtils.copy(file.getInputStream(), fos);
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }//

        String toHtmlFile = FileUtils.ossUploadFile(new File(filePath));

        //tbfile--start
        if (personService.getByDocId(documentId) == null) {
            TbFile tbFile = new TbFile();
            tbFile.setDocId(documentId);
            tbFile.setJobId(0);
            tbFile.setPersonId(personid);
            tbFile.setOriginal_name(fileName);
            tbFile.setNew_name(newFileName);
            tbFile.setFile_type(suffix);
            tbFile.setFile_path(filePath);
			/*if(toHtmlFile!=null){
				tbFile.setConvert_path("");
			}*/
            tbFile.setRelative_path(toHtmlFile);
            tbFile.setCreat_time(DateUtil.currentTime());
            tbFile.setUpdate_time(DateUtil.currentTime());
            tbFile.setCreate_by("1");
            tbFile.setUpdate_by("1");
            personService.saveFile(tbFile);
            //tbfile--end
        }

    }


    /**
     * 我要推荐==推荐他人
     *
     * @param response
     */
    @SuppressWarnings("unused")
    @RequestMapping(value = "Recommend")
    public void Recommend(HttpServletResponse response, int jobid, String unionid, String openid,
                          String name, Integer age, String companyname, String position, String phone, String comment, Integer roleid,
                          String formid) {
        int personId = 0;
        //unionid="oVCCz1AFLP-9mRGqOs8k_0w6V13Y";
        //String userphone=userService.getPhone(openid);
        Employee empemployee = employeeService.getEmpByUnionid(unionid);
        PersonRecom person = personService.getByPersonRecomPhone(phone);
        int empid = empemployee.getPersonId();
//		if(userphone!=null){
//			emp = employeeDAO.getEmpByPhone(userphone);
//			empid=emp.getPersonId();
//		}else{
//			pstemp=personDAO.getByPhone(userphone);
//			empid=pstemp.getId();
//		}
//		Person person=personDAO.getByPhone(phone);

        //boolean isExist = recommendService.isAlreadySelfRecommended(jobid, person.getId());
        //检查该候选人是否被推荐
        List<Recommendation> list = null;

        if (person == null) {
            Recommendation recommend = new Recommendation();
            recommend.setJobId(jobid);
            recommend.setReason("他人推荐");
            recommend.setPlatformId(1);
            // 推荐表里的createdby要用person的Id
            recommend.setCreateby(empid);
            if (person != null) {
                recommend.setPersonId(person.getId());
            } else {
                person = new PersonRecom();
                person.setOpenid(openid);
                person.setName(name);
                person.setPhone(phone);

                //candidate.setCityId(dto.getCityId());
                person.setAge(age);
                //candidate.setWorkage(dto.getWorkage());
                //candidate.setInservice(dto.getInservice());
                person.setPlatformId(1);
                person.setCompanyName(companyname);
                person.setComment(comment);
//				Company company = new Company();
//				company = companyDAO.getByName(companyname);
//				if(company == null) {
//					person.setCompanyId(0);
//					person.setCompanyName(companyname);
//				} else {
//					person.setCompanyId(company.getId());
//					person.setCompanyName(company.getName());
//				}
//				
                JobTitle role = jobTitleDAO.getByName(position);
                if (role == null) {
                    person.setRoleId(0);
                    person.setRoleName(position);
                } else {
                    person.setRoleId(role.getId());
                    person.setRoleName(role.getName());
                }
                personId = personService.savePersonRecom(person);
                recommend.setPersonId(personId);
            }
            Date now = new Date();
            recommend.setCreateDate(now.getTime());
            // 创建推荐信息
            int id = recommendService.createRecommendation(recommend);
            recommend.setId(id);
            //****新增一笔记录start*****/
            RecommendRecord record = new RecommendRecord();
            record.setRecommendId(id);
            record.setStatus(0);
            record.setRemark("已成功接收你的简历");
            record.setCreateTime(DateUtil.currentTime());
            Long saveres = recommendRecordDAO.save(record);
            //****新增一笔记录end***/
            JobDesc jobdesc = jobDAO.getById(jobid);
            String tempjson = new WxaTemplate()
                    .setTemplate_id("dPtEywT8RcESzRWxRRxwkowgafZISBAEqV3l6GPqJBQ")
                    .setForm_id(formid)
                    .setTouser(openid)
                    .setPage("pages/my-position/my-position")
                    .add("keyword1", name, "#000000")
                    .add("keyword2", jobdesc.getName(), "#000000")
                    .add("keyword3", DateUtil.currentTime(), "#000000")
                    .add("keyword4", "我们尽快给予回复，请耐心等候简历筛选反馈。", "#F47e2d")
                    .build();
            System.out.println(tempjson);
            boolean res = WxaTemplateUtil.sendTemplateYRCMsg(tempjson);
            System.out.println("模板消息发送结果：" + res);
            this.successJson(id, "推荐他人成功", response);

        } else {
            list = recommendDAO.getByJobAndPerson(jobid, person.getId());
            if (list != null && list.size() > 0) {
                this.successJson(list, "此候选人已经被推荐给该职位!", response);
            } else if (list == null || list.size() == 0) {//if(person.getPhone()!=null&&!person.getName().isEmpty()){
                Recommendation recommend = new Recommendation();
                recommend.setJobId(jobid);
                recommend.setReason("他人推荐");
                recommend.setPlatformId(1);
                // 推荐表里的createdby要用person的Id
                recommend.setPersonId(person.getId());
                recommend.setCreateby(empid);
                Date now = new Date();
                recommend.setCreateDate(now.getTime());
                // 创建推荐信息
                int id = recommendService.createRecommendation(recommend);
                recommend.setId(id);
                //****新增一笔记录end***/
                JobDesc jobdesc = jobDAO.getById(jobid);
                String tempjson = new WxaTemplate()
                        .setTemplate_id("dPtEywT8RcESzRWxRRxwkowgafZISBAEqV3l6GPqJBQ")
                        .setForm_id(formid)
                        .setTouser(openid)
                        .setPage("pages/my-position/my-position")
                        .add("keyword1", name, "#000000")
                        .add("keyword2", jobdesc.getName(), "#000000")
                        .add("keyword3", DateUtil.currentTime(), "#000000")
                        .add("keyword4", "我们尽快给予回复，请耐心等候简历筛选反馈。", "#F47e2d")
                        .build();
                System.out.println(tempjson);
                boolean res = WxaTemplateUtil.sendTemplateYRCMsg(tempjson);
                System.out.println("模板消息发送结果：" + res);
                this.successJson(id, "推荐他人成功", response);
            } else if (empid != 0) {
                this.successJson(1, "完善个人资料!", response);
            }

        }

    }

    /**
     * 推荐自己,应聘职位
     *
     * @param response
     * @param jobid
     * @param openid
     */
    @RequestMapping(value = "recommendme")
    public void recommendme(String unionid, HttpServletResponse response, int jobid, String openid, String formid, String sopenid) {
        logger.info("recommendme openid=" + openid);
        String msg = "";
        // 1:推荐中
        int status = 1;
//        openid = "oLmbP55b4Z-c-CGfiCScm6QNvyNg";
//        unionid="oVCCz1Pq8wSRRahut7hPi2MoKuZc";
        Recommendation recommend = new Recommendation();
        recommend.setJobId(jobid);
        recommend.setReason("自荐");
        recommend.setPlatformId(1);
        EmployeePerson emp = employeeService.getEmpPersonByUnionid(unionid);
        Person person = employeeService.getById(emp.getPersonId());
        // 推荐里的createby用person的id
        recommend.setCreateby(emp.getPersonId());
        Date now = new Date();
        recommend.setCreateDate(now.getTime());
        recommend.setPersonId(emp.getPersonId());
        recommend.setStatus(status);
        recommend.setRestype(1);
        recommend.setPhoneCreateDate(DateUtil.currentTime());
        recommend.setShareopenid(sopenid);
        //person.setAge(dto.getAge());
        //person.setWorkage(dto.getWorkage());

        //person.setInservice(dto.getInservice());

        // 更新自己的信息
        //employeeService.updateEmployeeProfile(emp,person);
        //Long count=recommendDAO.getDomainByMarch(emp.getMajorDomainId1(), emp.getMajorDomainId2(), emp.getMajorDomainId3());
        JobDesc jobdesc = jobDAO.getById(jobid);
        //List<EmployeePerson> ep=employeeService.searchEmployeesByJob(jobdesc,emp.getPersonId());
        List<EmployeePerson> ep1 = employeeService.searchEmployeesByJob1(jobdesc, emp.getPersonId());
        int ep = 0;
        for (int i = 0; i <= ep1.size(); i++) {
            if (ep1.size() <= 0) {
                List<EmployeePerson> ep2 = employeeService.searchEmployeesByJob2(jobdesc, emp.getPersonId());
                for (int j = 0; j <= ep2.size(); j++) {
                    if (ep2.size() <= 0) {
                        List<EmployeePerson> ep3 = employeeService.searchEmployeesByJob3(jobdesc, emp.getPersonId());
                        for (int k = 0; k <= ep3.size(); k++) {
                            if (ep3.size() > 0) {
                                ep = 1;
                            }
                        }
                    } else {
                        ep = 1;
                    }
                }
            } else {
                ep = 1;
            }
        }
        Company company = new Company();
        company = companyDAO.getById(person.getCompanyId());
        Company company2 = companyDAO.getById(jobdesc.getCompanyId());
        //formid 小程序已弃用
//        if (company == null) {
////			msg="感谢您的推荐，您所在公司不在我们的数据库内，需要后台审核，请等待！";
//            msg = "感谢您的投递，HR会尽快和您取得联系，您还可以考虑其他热招职位！";
//            //推送消息
//            String tempjson = new WxaTemplate()
//                    .setTemplate_id("tefJLXBKADN6YEELCf5znO3QyITxxk_ky8F0UwR0kMo")
//                    .setForm_id(formid)
//                    .setTouser(openid)
//                    .setPage("pages/my-position/my-position")
//                    .add("keyword1", "感谢您投递我们，您所在公司不在我们的数据库内，需要后台审核，请等待！", "#000000")
//                    .add("keyword1", jobdesc.getName(), "#000000")
//                    .add("keyword2", company2.getName(), "#000000")
//                    .add("keyword3", DateUtil.currentTime(), "#000000")
//                    .add("keyword", "请点击查看详情", "#00000")
//                    .build();
//            System.out.println(tempjson);
//            boolean res = WxaTemplateUtil.sendTemplateYRCMsg(tempjson);
//            System.out.println("模板消息发送结果：" + res);
//        } else if (ep == 1) {
//            status = 0;
//            msg = "感谢您的投递，HR会尽快和您取得联系，您还可以考虑其他热招职位！";
//            //推送消息
//            String tempjson = new WxaTemplate()
//                    .setTemplate_id("WxAJLfwX1uRW325CRKqjRFQHcO02T-B61dwN1DqBwhY")
//                    .setForm_id(formid)
//                    .setTouser(openid)
//                    .setPage("pages/my-position/my-position")
//                    .add("keyword1", jobdesc.getName(), "#000000")
//                    .add("keyword2", company2.getName(), "#000000")
//                    .add("keyword3", DateUtil.currentTime(), "#000000")
//                    .add("keyword4", "感谢您的投递，HR会尽快和您取得联系，您还可以考虑其他热招职位！", "#00000")
//                    .build();
//            System.out.println(tempjson);
//            boolean res = WxaTemplateUtil.sendTemplateYRCMsg(tempjson);
//            System.out.println("模板消息发送结果：" + res);
//        } else {
//            //自动设置
//            status = 3;
//            recommend.setStatus(status);
//            msg = "感谢您的投递，您的简历HR已收到，您还可以考虑其他热招职位！";
//            //推送消息
//            String tempjson = new WxaTemplate()
//                    .setTemplate_id("tefJLXBKADN6YEELCf5znO3QyITxxk_ky8F0UwR0kMo")
//                    .setForm_id(formid)
//                    .setTouser(openid)
//                    .setPage("pages/my-position/my-position")
//                    .add("keyword1", "感谢您的投递，您的简历HR已收到，您还可以考虑其他热招职位！", "#000000")
//                    .add("keyword2", jobdesc.getName(), "#000000")
//                    .add("keyword3", company2.getName(), "#000000")
//                    .add("keyword4", DateUtil.currentTime(), "#000000")
//                    .add("keyword5", "请点击查看详情", "#00000")
//                    .build();
//            System.out.println(tempjson);
//            boolean res = WxaTemplateUtil.sendTemplateYRCMsg(tempjson);
//            System.out.println("模板消息发送结果：" + res);
//
//        }

        // 创建推荐信息
        int recommendmeId = recommendService.createRecommendation(recommend);
        recommend.setId(recommendmeId);
        //push hunter
        Employer employer = userService.getEmployerId(jobdesc.getCreatedby());
        String tempjsonhunter = TemplateData.New()
                .setTouser(employer.getOpenid())
                .setTemplate_id("IFTCljrBeL4Ef8alZUDQlZqwLafadkX5APawYS4K4_U")
                //.setUrl("https://www.tiaonali.com/tnl-hunter/wechat/hunter/hr/toViewCandidate.do?jobid="+jobdesc.getId()+"&empid="+person.getId()+"&recommendid="+recommendmeId)
                .setUrl("https://www.tiaonali.com/tnl-hunter/wechat/hunter/hr/toInterview.do?recommendid=" + recommendmeId)
                .add("first", "您有一份新的简历，请及时查阅", "#274084")
                .add("keyword1", jobdesc.getName(), "#000000")
                .add("keyword2", person.getName(), "#F47e2d")
                .add("keyword3", person.getWorkage().toString(), "#000000")
                .add("remark", "请点击查看详情", "#274084")
                .build();
        System.out.println(tempjsonhunter);
        ApiResult reshunter = TemplateMsgApi.send(tempjsonhunter);
        System.out.println("模板消息发送结果：" + reshunter);
        if (status == 3 || status == 1) {
            //****新增一笔记录start*****/
            RecommendRecord record = new RecommendRecord();
            record.setRecommendId(recommendmeId);
            record.setStatus(status);
            switch (status) {
                case 1:
                    record.setRemark("已成功接收你的简历");
                    break;
                case 3:
                    record.setRemark("简历标记为不合适");
                    break;
                default:
                    break;
            }
            record.setCreateTime(DateUtil.currentTime());
            Long saveres = recommendRecordDAO.save(record);
            //****新增一笔记录end***/
        }
        //insert interview init

        /*
         * Interview itv = new Interview(); itv.setRecommendId(recommendmeId);
         * itv.setItype(5); itv.setStatus(1); itv.setCreateTime(now.getTime());
         * itv.setUpdateTime(new java.sql.Date(now.getTime())); Long interviewId =
         * interViewDAO.save(itv); itv.setId(interviewId.intValue());
         */
        //send mail
        if (jobdesc.getJobContact() != null) {
            mailService.sendMail(jobdesc.getJobContact(), jobdesc.getName(),
                    StrUtils.replaceNameX(person.getName()), StrUtils.replacePhone(person.getPhone()));
        }
        this.successJson(recommendmeId, msg, response);
    }

    /**
     * 查询我的职位
     *
     * @param response
     */
    @RequestMapping(value = "myrecommend")
    public void myrecommand(HttpServletResponse response, String openid, String unionid) {
        JSONObject json = new JSONObject();
        //unionid="oVCCz1LdYLYknfVIEx6gcg40FGZg";
        //String userphone=userService.getPhone(openid);
        //Person person=userService.getPersonId(userphone);
        Employee emp = employeeService.getEmpByUnionid(unionid);
		
		/*if(person==null){
			emp = employeeDAO.getEmpByPhone(userphone);
			pid=emp.getPersonId();
		}else{
			pid=person.getId();
		}*/

        if (emp != null) {
            int pid = emp.getPersonId();
            List<Recommend> otherRecomm = jobDAO.getOtherRecommendByJob(pid);
            for (Recommend recomm : otherRecomm) {
                if (recomm.getPersonId() != recomm.getCreateby()) {
                    //处理职位信息
                    JobDesc job = jobDAO.getById(recomm.getJobId());
                    recomm.setJobName(job.getName());
                    recomm.setReward(job.getReward());
                    City city = cityDAO.getById(job.getCityId());
                    recomm.setCityName(city.getName());
                    Company company = companyDAO.getById(job.getCompanyId());
                    recomm.setCompanyName(company.getName());
                    long data = job.getExpiredDate();
                    recomm.setExpiredDateStr(DateUtil.getDateStr(data));
                    PersonRecom personrecomm = personService.getByPersonRecomId(recomm.getPersonId());
                    if (personrecomm != null) {
                        recomm.setPersonName(personrecomm.getName() != null ? personrecomm.getName() : "");
                        recomm.setPhone(personrecomm.getPhone() != null ? personrecomm.getPhone() : "");
                    }
                    if (recomm.getStatus() == 0) {
                        recomm.setStatusStr("已推荐");
                    } else if (recomm.getStatus() == 1) {
                        recomm.setStatusStr("推荐中");
                    } else if (recomm.getStatus() == 2) {
                        recomm.setStatusStr("推荐成功");
                    } else if (recomm.getStatus() == 3) {
                        recomm.setStatusStr("推荐失败");
                    } else if (recomm.getStatus() == 4) {
                        recomm.setStatusStr("被查看");
                    } else if (recomm.getStatus() == 5) {
                        recomm.setStatusStr("有意向关注中");
                    } else if (recomm.getStatus() == 6) {
                        recomm.setStatusStr("职位沟通待您确认");
                    } else if (recomm.getStatus() == 7) {
                        recomm.setStatusStr("同意沟通");
                    } else if (recomm.getStatus() == 8) {
                        recomm.setStatusStr("不同意沟通");
                    }
                }
            }
            json.put("otherrecomm", otherRecomm);
            List<Recommend> selfrecomm = jobDAO.getRecommendByJob(pid);
            for (Recommend recomm1 : selfrecomm) {
                if (recomm1.getPersonId() == recomm1.getCreateby()) {
                    //处理职位信息
                    JobDesc job = jobDAO.getById(recomm1.getJobId());
                    recomm1.setJobName(job.getName());
                    recomm1.setReward(job.getReward());
                    City city = cityDAO.getById(job.getCityId());
                    recomm1.setCityName(city.getName());
                    Company company = companyDAO.getById(job.getCompanyId());
                    recomm1.setCompanyName(company.getName());
                    long data = job.getExpiredDate();
                    recomm1.setExpiredDateStr(DateUtil.getDateStr(data));
                    Person personrecomm = employeeService.getById(recomm1.getPersonId());
                    if (personrecomm != null) {
                        recomm1.setPersonName(personrecomm.getName());
                        recomm1.setPhone(personrecomm.getPhone());
                    }
                    if (recomm1.getStatus() == 0) {
                        recomm1.setStatusStr("已应聘");
                    } else if (recomm1.getStatus() == 1) {
                        recomm1.setStatusStr("面试");
                    } else if (recomm1.getStatus() == 2) {
                        recomm1.setStatusStr("面试成功");
                    } else if (recomm1.getStatus() == 3) {
                        recomm1.setStatusStr("不合适");
                    } else if (recomm1.getStatus() == 4) {
                        recomm1.setStatusStr("被查看");
                    } else if (recomm1.getStatus() == 5) {
                        recomm1.setStatusStr("有意向关注中");
                    } else if (recomm1.getStatus() == 6) {
                        recomm1.setStatusStr("职位沟通待您确认");
                    } else if (recomm1.getStatus() == 7) {
                        recomm1.setStatusStr("同意沟通");
                    } else if (recomm1.getStatus() == 8) {
                        recomm1.setStatusStr("不同意沟通");
                    }
                }
            }
            json.put("selfrecomm", selfrecomm);
        }
        this.successJson(json, "已推荐职位", response);
    }

    /**
     * 该人的推荐是否已经存在
     *
     * @param response
     * @param jobid
     * @param empid
     */
    @RequestMapping(value = "isExistRecommendme")
    public void isExist(HttpServletResponse response, int jobid, int empid) {
        boolean isExist = recommendService.isAlreadySelfRecommended(jobid, empid);
        this.successJson(isExist, "检查该职位，该人的推荐是否已经存在", response);
    }

    private void insertUser(WxAppUser wxappUser, String openId) {
        Long isOpenId = wxAppUserDAO.getOpenId(openId);
        if (isOpenId == 0) {
            wxAppUserDAO.save(wxappUser);
        } else {
            WxAppUser appUser = wxAppUserDAO.getByOpenId(openId);
            if (wxappUser != null) {
                wxAppUserDAO.update(wxappUser);
                System.out.println("NOT equals!!!!");
            } else {
                System.out.println("OK !!!");
            }
        }

    }

    /**
     * 发送验证码
     *
     * @param response
     * @param openid
     * @param phone
     */
    @RequestMapping(value = "sendCode")
    public void sendCode(HttpServletResponse response, String openid, String phone) {
        String result = null;
        WxAppUser user = wxAppUserDAO.getByOpenId(openid);
        Employee emp = employeeService.getEmpByPhone(phone);
        JSONObject json = new JSONObject();
        String secureCode = null;
        if (emp != null && user != null) {
            secureCode = emp.getSecureCode();
        } else if (user == null && emp != null) {
            secureCode = emp.getSecureCode();
            wxAppUserDAO.savecode(phone, openid);
        } else {
            RadomUtils radom = new RadomUtils();
            secureCode = radom.getRadom(4);
            emp = new Employee();
            if (user != null) {
                emp.setName(user.getNickname());
            }
            emp.setOpenid(openid);
            emp.setPhone(phone);
            emp.setActive(1);
            emp.setSecureCode(secureCode);// 重复的
            emp.setState(Person.State.generated.toString());

            java.util.Date timeDate = new Date();// util类型
            long time = timeDate.getTime();
            java.sql.Timestamp dateTime = new java.sql.Timestamp(time);// Timestamp类型,timeDate.getTime()返回一个long型

            emp.setExpiredTime(dateTime);
            employeeService.saveSecureCode(emp);
            wxAppUserDAO.savecode(phone, openid);
        }
        // send out code
        try {
            System.out.println("验证码：" + secureCode);
            result = smsService.sendSMS(phone, secureCode);
            json.put("result", result);
            json.put("secureCode", secureCode);
        } catch (Exception e) {
            e.printStackTrace();
            this.errorJson(json, "验证已发送，请您及时填写。", response);
        }
        this.successJson(json, "验证已发送，请您及时填写。", response);
    }

    // 绑定Phone
    @RequestMapping(value = "bindePhone")
    public void bindedPhone(HttpServletResponse response, String openid, String phone, String inputCode) {
        Employee emp = employeeService.getEmpByPhone(phone);
        if (emp == null) {
            this.errorJson(emp, "请重新申请验证码", response);
        } else {
            String secureCode = emp.getSecureCode();
            if (inputCode.equalsIgnoreCase(secureCode)) {
                if (emp.getActive() == 0) {
                    emp.setActive(1);
                    emp.setPhone(phone);
                    long empId = employeeService.bindedPhone(emp);
                    if (empId >= 0) {
                        this.successJson(empId, "成功更新了信息", response);
                    } else {
                        this.errorJson(empId, "验证失败,注册信息有误", response);
                    }
                }
            }
            this.errorJson(emp, "验证失败，请填写正确的验证码", response);
        }
    }

    /**
     * 职位沟通确认修改状态
     * status7:同意；8：不同意；
     *
     * @param response
     * @param status
     * @param recommendid
     */
    @RequestMapping(value = "updatePosiStatus")
    public void updatePosiStatus(HttpServletResponse response, int status, int recommendid) {
        int res = recommendDAO.updateStatus(status, recommendid);
        //****新增一笔记录start*****/
        RecommendRecord record = new RecommendRecord();
        record.setRecommendId(recommendid);
        record.setStatus(recommendid);
        switch (status) {
            case 7:
                record.setRemark("同意职位沟通");
                break;
            case 8:
                record.setRemark("不同意职位沟通");
                break;
            default:
                break;
        }
        record.setCreateTime(DateUtil.currentTime());
        Long saveres = recommendRecordDAO.save(record);
        //****新增一笔记录end***/
        if (res == 1) {
            this.successJson(res, "update success", response);
        } else {
            this.errorJson(res, "update fail", response);
        }
    }

    /**
     * 简历跟踪流程
     *
     * @param response
     * @param recommendId
     */
    public void deliverflow(HttpServletResponse response, int recommendId) {
        JSONObject json = new JSONObject();
        List<RecommendRecord> recommendRecords = recommendRecordDAO.getALL(recommendId);
        for (RecommendRecord recommendRecord : recommendRecords) {
            Interview interview = interViewRecordDAO.getRecommendIdByInfo(recommendRecord.getRecommendId());
            if (interview.getId() > 0) {
                List<InterviewRecord> interviewRecords = interViewRecordDAO.getALL(interview.getId());
                json.put("interview", interviewRecords);
            }
        }
        json.put("recommend", recommendRecords);
        this.successJson(json, "deliverflow", response);
    }

    /**
     * web登录
     *
     * @param response
     */
    @RequestMapping(value = "toWebOauth")
    public void toWebOauth(HttpServletResponse response) {
        String calbackUrl = SystemConfig.getProperties("domain") + "/tnl-wxapp/oauth/webCallBack";
        String url = SnsAccessTokenApi.getQrConnectURL(SystemConfig.getProperties("webAppId"), calbackUrl, "666");
        logger.info(url);
        this.successJson(url, "web oauth", response);

    }

    /**
     * 公司分类（Top500强/行业新贵）
     *
     * @param response
     */
    @RequestMapping(value = "companyTagsPosi")
    public void companyTagsPosi(HttpServletResponse response, String param, Integer page, Integer size, String tags) {
        City c = cityDAO.getByName(param);
        if (c != null) {
            param = c.getId() + "";
        }
        int totalNum = jobDAO.getTotalNumForcompanyTagsPosi(param, tags);
        int pageNum = getPageNum(totalNum, size);
        int offset = (page - 1) * size;
        List<JobDesc> job = jobDAO.companyTagsPosi(offset, size, param, tags);
        if (job != null && job.size() > 0) {
            for (JobDesc jobDesc : job) {
                // get city
                int cityId = jobDesc.getCityId();
                City city = cityDAO.getById(cityId);
                jobDesc.setCityName(city.getName());
                // get company
                Company company = companyDAO.getById(jobDesc.getCompanyId());
                jobDesc.setCompanyName(company.getName());
                jobDesc.setEnterprise_logo(company.getLogoIcon());
                Domain domain = domainDAO.getById(jobDesc.getDomainID());
                if (domain != null) {
                    jobDesc.setDomainName(domain.getName());
                }
                // get expiredate
                long data = jobDesc.getExpiredDate();
                jobDesc.setExpiredDateStr(DateUtil.getDateStr(data));
                jobDesc.setCreateTime(DateUtil.getDateStr(jobDesc.getCreateDate()));
            }
        }
        job.stream().parallel().filter(s -> !StringUtils.isEmptyOrWhitespaceOnly(s.getKeywords())).peek(s -> {
            setKeyWords(s);
        }).collect(Collectors.toList());

        this.successJson(new PageVo(job, pageNum), "Top 500", response);
    }

    /**
     * 超高薪酬
     *
     * @param response
     * @param page
     * @param size
     */
    @RequestMapping(value = "highSalaryPosi")
    public void highSalaryPosi(HttpServletResponse response, String param, Integer page, Integer size) {
        City c = cityDAO.getByName(param);
        if (c != null) {
            param = c.getId() + "";
        }

        Integer reward = 500;
        int totalNum = jobDAO.getTotalNumForHighSalayPosi(param, reward);
        int pageNum = getPageNum(totalNum, size);
        int offset = (page - 1) * size;
        List<JobDesc> job = jobDAO.highSalayPosi(offset, size, param, reward);
        for (JobDesc jobDesc : job) {
            // get city
            int cityId = jobDesc.getCityId();
            City city = cityDAO.getById(cityId);
            jobDesc.setCityName(city != null ? city.getName() : "");
            // get company
            Company company = companyDAO.getById(jobDesc.getCompanyId());
            jobDesc.setCompanyName(company != null ? company.getName() : "");
            jobDesc.setEnterprise_logo(company != null ? company.getLogoIcon() : "");
            Domain domain = domainDAO.getById(jobDesc.getDomainID());
            if (domain != null) {
                jobDesc.setDomainName(domain.getName());
            }
            // get expiredate
            long data = jobDesc.getExpiredDate();
            jobDesc.setExpiredDateStr(DateUtil.getDateStr(data));
            jobDesc.setCreateTime(DateUtil.getDateStr(jobDesc.getCreateDate()));
        }
        job.stream().parallel().filter(s -> !StringUtils.isEmptyOrWhitespaceOnly(s.getKeywords())).peek(s -> {
            setKeyWords(s);
        }).collect(Collectors.toList());
        this.successJson(new PageVo(job, pageNum), "High Salary", response);
    }

    @RequestMapping(value = "searchPosi")
    public void searchPosi(HttpServletResponse response, Integer page, Integer size, String searchName) {
        int totalNum = jobDAO.getTotalNumForSearchPosi(searchName);
        int pageNum = getPageNum(totalNum, size);
        int offset = (page - 1) * size;
        List<JobDesc> job = jobDAO.searchPosi(offset, size, searchName);
        for (JobDesc jobDesc : job) {
            // get city
            int cityId = jobDesc.getCityId();
            City city = cityDAO.getById(cityId);
            jobDesc.setCityName(city.getName());
            // get company
            Company company = companyDAO.getById(jobDesc.getCompanyId());
            jobDesc.setCompanyName(company.getName());
            jobDesc.setEnterprise_logo(company.getLogoIcon());
            Domain domain = domainDAO.getById(jobDesc.getDomainID());
            if (domain != null) {
                jobDesc.setDomainName(domain.getName());
            }
            // get expiredate
            long data = jobDesc.getExpiredDate();
            jobDesc.setExpiredDateStr(DateUtil.getDateStr(data));
            jobDesc.setCreateTime(DateUtil.getDateStr(jobDesc.getCreateDate()));
        }
        job.stream().parallel().filter(s -> !StringUtils.isEmptyOrWhitespaceOnly(s.getKeywords())).peek(s -> {
            setKeyWords(s);
        }).collect(Collectors.toList());
        this.successJson(new PageVo(job, pageNum), "High Salary", response);
    }

    @Cacheable("cityCache")
    @RequestMapping(value = "getCities")
    public void getCities(HttpServletResponse response) {
        List<City> cityList = cityDAO.getALL();
//        Comparator<Object> com= Collator.getInstance(java.util.Locale.CHINA);
//        Collections.sort(cityList,new Comparator<City>() {
//            @Override
//            public int compare(City info1, City info2) {
//                return com.compare(info1.getName(), info2.getName());
//            }
//        });
        this.successJson(cityList, "city", response);
    }

    @Cacheable("domainCache")
    @RequestMapping(value = "getDomains")
    public void getDomains(HttpServletResponse response) {
        List<Domain> domainList = domainDAO.getAllSubDomain();
        this.successJson(domainList, "domain", response);
    }

    @RequestMapping(value = "getDomainList")
    public void getDomainList(int i, HttpServletResponse response) {
        List<Domain> domainList = domainDAO.getAllSubDomain(i);
        this.successJson(domainList, "domain", response);
    }

    @RequestMapping(value = "getJobs")
    public void getJobs(String name, HttpServletResponse response) {
        List<JobTitle> list = jobTitleDAO.getListByName(name);
        this.successJson(list, "job", response);
    }

    @RequestMapping(value = "getCompanys")
    public void getCompanys(String name, int i, HttpServletResponse response) {
        List<Company> companys = companyDAO.getOptions2(name, i);
        List<Map<String, Object>> list = new ArrayList<>();
        if (companys != null && companys.size() > 0) {
            companys.forEach(c -> {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("value", c.getId());
                map.put("label", c.getName());
                list.add(map);
            });
        }
        this.successJson(list, "company", response);
    }

    @RequestMapping(value = "listJobByParam")
    public void listJobByParam(Integer dId, Integer fId, String companys, String positions, Integer city, String positionName, HttpServletResponse response, Integer page, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        logger.info("request query position with param:domainId{} functionId:{}, companys:{}, positions:{}", dId, fId, companys, positions);
        if (((dId == null && fId == null || dId.intValue() == 0 && fId.intValue() == 0)) && StringUtils.isEmptyOrWhitespaceOnly(companys) && StringUtils.isNullOrEmpty(positions)) {
            this.successJson(null, "最新职位主页展示", response);
            return;
        }
        List<Integer> companyIds = null;
        if (!StringUtils.isEmptyOrWhitespaceOnly(positionName)) {
            List<Company> companyList = companyDAO.searchCompany(0, 100, positionName);
            if (companyList != null && companyList.size() > 0) {
                companyIds = companyList.parallelStream().map(Company::getId).collect(Collectors.toList());
            }
        }


        int totalNum = jobDAO.getJobCountByParam(companyIds,positions, companys, dId, fId, city, positionName);
        int pageNum = getPageNum(totalNum, pageSize);
        int offset = (page - 1) * pageSize;


        List<JobDesc> job = jobDAO.listJobByParam(companyIds, positions, companys, dId, fId, city, positionName, offset, pageSize);
        for (JobDesc jobDesc : job) {
            // get city
            int cityId = jobDesc.getCityId();
            City cityObject = cityDAO.getById(cityId);
            if (city != null) {
                jobDesc.setCityName(cityObject.getName());
            }
            // get company
            Company company = companyDAO.getById(jobDesc.getCompanyId());
            if (company != null) {
                jobDesc.setCompanyName(company.getName());
                jobDesc.setEnterprise_logo(company.getLogoIcon());
            }

            // get expiredate
            long data = jobDesc.getExpiredDate();
            jobDesc.setExpiredDateStr(DateUtil.getDateStr(data));
            // get domain
            Domain domain = domainDAO.getById(jobDesc.getDomainID());
            if (domain != null) {
                jobDesc.setDomainName(domain.getName());
            }
            jobDesc.setCreateTime(DateUtil.getDateStr(jobDesc.getCreateDate()));
        }
        job.stream().parallel().filter(s -> !StringUtils.isEmptyOrWhitespaceOnly(s.getKeywords())).peek(s -> {
            setKeyWords(s);
        }).collect(Collectors.toList());
        this.successJson(job, "最新职位主页展示", response);
    }


    @RequestMapping(value = "getFirstBanner")
    public void getFirstBanner(String pictureId, HttpServletResponse response) {
        SysPicture picture = sysPictureDao.getById(pictureId);
        this.successJson(picture, "banner", response);
    }

    @RequestMapping("/sendMail")
    @ResponseBody
    public void sendEmail(String mail, String fileupd, HttpServletResponse response) {
        String uri = "https://tiaonali.com/" + fileupd;
        System.out.println("简历邮件推送，参数mail:" + mail + "文件地址：" + uri);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(mail) &&
                org.apache.commons.lang3.StringUtils.isNotBlank(fileupd)) {
            String content = "尊敬的客户，您好！<br/>您咨询的简历撰写服务，已收到顾问的反馈。请点击<a target='_blank' href=" + uri + ">链接地址</a>进行下载!";
            MailUtils.sendAttachmentMail(mail, "顾问简历反馈", content, "");
        }
    }
}
